﻿module Sustainalytics.GCCS {

    import Common = Sustainalytics.Common;
    import Pager = Sustainalytics.Pager;

    export class GCMultiCompanyReportController {

        // order by
        public orderByCol: string;
        public orderByAsc: boolean;

        // list of multi company reports
        public companyReportList: GCOverallCompanySummaryExtendedDto[];
        public overallAssessments: { name: string; value: number; selected:boolean; disabled:boolean}[];
        public selectedAssessment: GCAssessment;
        public gcPermissions: GCCS.Security.GCPermissions;
        
        // total number of results
        public companyReportCount: number;

        private scopeDestroyed: boolean;

        private $routeParams: any;

        //filter options
        public overallAssessmentOptions: any[] = [
            { value: GCAssessment.NonCompliant, text: 'Non Compliant' },
            { value: GCAssessment.Watchlist, text: 'Watchlist' },
        ];

        public gcPrinciplesOptions: any[] = [];
        public myEvents: any;

        //filter values

        public gcPrinciplesNCFilter: any[] = [];
        public gcPrinciplesWLFilter: any[] = [];

        //filter value object
        public gcFilter: GCOverallCompanySummaryExtendedFilters = new GCOverallCompanySummaryExtendedFilters();


        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            //private $routeParams: ng.route.IRouteParamsService,
            private RoutingService: Routing.IRoutingService,
            private GCOverallCompanySummaryExtendedService: IGCOverallCompanySummaryExtendedService,
            private GCPermissionsService: GCCS.Security.IGCPermissionsService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects) {

            var ctx = this;
            ctx.myEvents = {
                onMultiSelectBlur: function () {
                    ctx.searchButtonClick();
                }
            };

            ctx.$routeParams = ctx.RoutingService.getRouteParams();
            $scope['gcMultiCompanyReportCtrl'] = ctx;

            ctx.scopeDestroyed = false;
            ctx.selectedAssessment = null;
            ctx.gcPermissions = ctx.GCPermissionsService.getPermissions();
            /////////////////////////
            //ctx.gcPermissions.hasMultiCompWL = false;////////////////


            //initialize gcPrinciplesOptions
            ctx.gcPrinciplesOptions.push({ id: 0, label: "N/A" });
            for (var i = 0; i < 7; i++) {
                ctx.gcPrinciplesOptions.push({ id: i + 1, label: "Principle " + (i + 1).toString() });
            }
            ctx.gcPrinciplesOptions.push({ id: 10, label: "Principle 10" });
            //end initialize gcPrinciplesOptions


            ctx.initOverallAssessments();

            ctx.orderByCol = "companyProfile.nameLowercase";
            ctx.orderByAsc = true;
            ctx.handleScopeDestroyed();
            ctx.handlePagerChanged();
            
        }

        private initOverallAssessments() {
            var ctx = this;

            // init the list of overall assessments
            ctx.overallAssessments =
            [
                { name: "Non-Compliant List", value: GCAssessment.NonCompliant, selected: false, disabled: false },
                { name: "Watchlist", value: GCAssessment.Watchlist, selected: false, disabled: false },
                { name: "Non-Compliant and Watchlist", value: null, selected: true, disabled: false }
            ];


            // select default overall assessment
            if (ctx.gcPermissions.hasMultiCompNC && ctx.gcPermissions.hasMultiCompWL) {
                ctx.selectOverallAssessment(null);
            }
            else {
                if (ctx.gcPermissions.hasMultiCompNC) {
                    ctx.selectOverallAssessment(GCAssessment.NonCompliant);
                    ctx.overallAssessments[1].disabled = true;
                    ctx.overallAssessments[2].disabled = true;
                }
                if (ctx.gcPermissions.hasMultiCompWL) {
                    ctx.selectOverallAssessment(GCAssessment.Watchlist);
                    ctx.overallAssessments[0].disabled = true;
                    ctx.overallAssessments[2].disabled = true;
                }
            }


            // get overall assessment from URI
            var uriOverallAssessmentStr = ctx.$routeParams['overallAssessment'];
            uriOverallAssessmentStr = uriOverallAssessmentStr ? uriOverallAssessmentStr.toLowerCase() : null;

            // select overall assessment
            switch (uriOverallAssessmentStr) {
                case 'noncompliant':
                    if (!ctx.overallAssessments[GCAssessment.NonCompliant].disabled) {
                        ctx.selectOverallAssessment(GCAssessment.NonCompliant);
                    }
                    break;
                case 'watchlist':
                    if (!ctx.overallAssessments[GCAssessment.Watchlist].disabled) {
                        ctx.selectOverallAssessment(GCAssessment.Watchlist);
                    }
                    break;
                case 'all':
                    if (!ctx.overallAssessments[GCAssessment.Compliant].disabled) {
                        ctx.selectOverallAssessment(null);
                    }
                    break;
            }
        }


        // when scope is destroyed keep a flag to prevent some operations
        // eg: bootstrap UI tab delete each tab and select the next that causing 
        // in current case to trigger multiple requests while tabs are being disposed 
        // which is unnecessary
        private handleScopeDestroyed() {
            var ctx = this;

            // when scope is destroyed
            ctx.$scope.$on('$destroy', function () {
                ctx.scopeDestroyed = true;
            });
        }


        private handlePagerChanged() {
            var ctx = this;

            ctx.$scope.$on('pagerChanged', function (ev, pager: Pager.PagerController) {
                ctx.getCompanyReports(ctx.selectedAssessment);
            });
        }

        private selectOverallAssessment(assessmentValue: GCAssessment) {
            var ctx = this;

            for (var i = 0; i < ctx.overallAssessments.length; i++) {
                ctx.overallAssessments[i].selected = false;
            }

            switch (assessmentValue) {
                case GCAssessment.NonCompliant:
                    ctx.selectedAssessment = GCAssessment.NonCompliant;
                    ctx.overallAssessments[0].selected = true;
                    break;
                case GCAssessment.Watchlist:
                    ctx.selectedAssessment = GCAssessment.Watchlist;
                    ctx.overallAssessments[1].selected = true;
                    break;
                case null:
                    ctx.selectedAssessment = null;
                    ctx.overallAssessments[2].selected = true;
                    break;
                default:
                    ctx.selectedAssessment = null;
            }
        }

        private getReportByAssessment(assessmentValue: number) {
            var ctx = this;
            
            //reset gcFilter, state variables and filter columns
            for (var prop in ctx.gcFilter) {
                ctx.gcFilter[prop] = null;
            }

            ctx.gcPrinciplesNCFilter = [];
            ctx.gcPrinciplesWLFilter = [];

            ctx.orderByCol = "companyProfile.nameLowercase";
            ctx.orderByAsc = true;
            //

            ctx.selectOverallAssessment(assessmentValue);
            ctx.getCompanyReports(ctx.selectedAssessment, true);
        }

        private redirectToCompanyPage(companyName: string, assesmentValue: number) {
            var ctx = this;
            var overallAssesment = GCCS.GCUtility.getGcAssessmentUrlName(assesmentValue);
            ctx.$location.path('/research/globalcompact/company/' + companyName + '/' + overallAssesment);
        }

        // order list of portfolios
        public setOrderByCol(col: string) {
            var ctx = this;

            if (ctx.orderByCol === col) {
                ctx.orderByAsc = !ctx.orderByAsc;
            }
            else {
                ctx.orderByCol = col;
                ctx.orderByAsc = true;
            }
            ctx.getCompanyReports(ctx.selectedAssessment, true);
        }

        public searchButtonClick() {
            var ctx = this;

            // go to page 1
            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager)
                return;

            pager.goTo(1);
        }

        public getGCCSAssesmentByValue(val: number) {
            var ctx = this;
            return ctx.staticObjects.getGCCSAssesmentByValue(val);
        }

        public assessementHasClaims(val: number) {
            var ctx = this;
            switch (val) {
            case 1:
                return ctx.gcPermissions.hasMultiCompNC;
            case 2:
                return ctx.gcPermissions.hasMultiCompWL;
            case null:
                return ctx.gcPermissions.hasMultiCompNC && ctx.gcPermissions.hasMultiCompWL;
            default:
                return false;
            }
        }

        public getCompanyReports(overallAssessment?: GCAssessment, resetPager: boolean = false): ng.IPromise<Common.PagedList<GCOverallCompanySummaryExtendedDto>> {

            var ctx = this;
            ctx.$rootScope['loading'] = true;

            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager) {
                var def = ctx.$q.defer();
                def.reject();
                return def.promise;
            }

            if (resetPager) {
                pager.goTo(1);
            }

            var skip = pager.skipCount();
            var take = pager.takeCount();

            //prepare filter object
            ctx.gcFilter.companyNameLowerCase = angular.lowercase(ctx.gcFilter.companyNameLowerCase);
            ctx.gcFilter.industry = angular.lowercase(ctx.gcFilter.industry);

            ctx.gcFilter.principlesNCStrFilter = "";
            if (ctx.gcPrinciplesNCFilter && ctx.gcPrinciplesNCFilter.length > 0) {
                var temp: string[] = [];
                ctx.gcPrinciplesNCFilter.forEach(obj => {
                    temp.push(obj.id);
                    ctx.gcFilter.principlesNCStrFilter = temp.join("|");
                });
            }

            ctx.gcFilter.principlesWLStrFilter = "";
            if (ctx.gcPrinciplesWLFilter && ctx.gcPrinciplesWLFilter.length > 0) {
                var temp: string[] = [];
                ctx.gcPrinciplesWLFilter.forEach(obj => {
                    temp.push(obj.id);
                    ctx.gcFilter.principlesWLStrFilter = temp.join("|");
                });
            }

            if (!resetPager) {

                var pagedListPromise: ng.IPromise<Common.PagedList<GCOverallCompanySummaryExtendedDto>> =
                    ctx.GCOverallCompanySummaryExtendedService.GetPagedLst(ctx.gcFilter, skip, take, [ctx.orderByCol], ctx.orderByAsc, overallAssessment);

                pagedListPromise
                    .then(function (pagedList: Common.PagedList<GCOverallCompanySummaryExtendedDto>) {
                        ctx.companyReportList = pagedList.items;
                        ctx.companyReportCount = pagedList.totalItemsCount;
                        pager.setTotalItemsCount(pagedList.totalItemsCount);
                    })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });

                return pagedListPromise;
            }
        }
    }


    // register controller with GCCS module
    angular.module('Sustainalytics.GCCS').controller('GCMultiCompanyReportController',
        ['$rootScope', '$scope', '$q', '$location', 'RoutingService', 'GCOverallCompanySummaryExtendedService', 'GCPermissionsService',
            'notificationFactory', 'staticObjects', GCMultiCompanyReportController]);
} 